<?php
error_reporting(-1);
ini_set('display_errors', 1);
/** 
 * 后台_用户_控制器
 * @property User_mdl $users
 * @property Test_user_mdl $testUser
 * @property School_mdl $school
 * @property Prepayment_log_mdl $prepaymentLog
 */
class User extends Admin_Controller {

	public function __construct() {
		parent::__construct ();
		$this->load->model('User_mdl','users');
		$this->load->model('School_mdl','school');
	}
	
	public function index(){
		$this->load->library('Search_tpl',NULL,'searchTpl');
		$where = array();
		$like  = array();
		$order = 'id';
		$sort  = 'DESC';
		$orders = array(
				'uid'=>'id',
				'time'=>'regTime',
		);
		$input = $this->input->get(NULL,TRUE);
		foreach ($input as $k=>$v){
			if ($v===''){
				continue;
			}
			$v = trim($v);
			switch ($k) {
				case 'uid':
					$where['id'] = (int)$v;
					break;
				case 'nickname':
					$like['nickname'] = $v;
					break;
				case 'schoolID' : 
					$v = (int)$v;
					if( $v > 0 ){
						$where['schoolID'] = $v;
					}
					break;
				case 'order' :
					$order = isset($orders[$v]) ? $orders[$v] : 'id';
					break;
				case 'sort':
					$sort = (int)$v===0 ? 'DESC' : 'ASC';
					break;
				case 'phone':
					$where['phone'] = (float)$v;
					break;
				case 'reg_st':
					$where['regTime >'] = strtotime($v);
					break;
				case 'reg_et':
					$where['regTime <'] = strtotime($v);
					break;
			}
		}
		$query = array();
		$query['select']= '*';
		$query['from']  = MY_Model::T_USER;
		$query['where'] = $where;
		$query['like']  = $like;
		$query['order'] = $order;
		$query['sort']  = $sort;
		$this->searchTpl->query($query);
		$temp = array();
		$temp['formItems'] = array(
				'uid',
				'nickname',
				'phone',
				'school',
				'br',
				array('type'=>'dateRange','label'=>'注册时间','name'=>array('reg_st','reg_et')),
				
		);
		$temp ['thList'] = array (
				array('text'=>'用户ID','order'=>'uid'),
				'用户昵称',
				'可用余额',
				'累计充值',
				'累计消费',
				'累计赠送',
				'预付款余额',
				'权限',
				'手机号码',
				'学校',
				'注册时间',
// 				'绑定微信',
		);
		
		$schoolList = $this->school->getSchoolList();
		
// 		pr($schoolList);die;
		
		$callback = function($v)use($schoolList){
			return array(
					$v['id'],
					$v['nickname'],
					array('val'=>$v['balance']/100,'class'=>'amount'),
					array('val'=>$v['rechargeTotal']/100,'class'=>'amount'),
					array('val'=>$v['buyTotal']/100,'class'=>'amount'),
					array('val'=>$v['presrent']/100,'class'=>'amount'),
					array('val'=>$v['prepayment']/100,'class'=>'amount'),
					$v['isTest'] ? '调试人员' : '普通用户',
					$v['phone'],
					empty($schoolList[$v['schoolID']]) ? '' : $schoolList[$v['schoolID']]['name'],
					date('Y-m-d H:i:s',$v['regTime']),
// 					empty($v['wxOpenID']) ? '否' : '是',
			);
		};
		$temp['tableTitle'] = '用户列表--共查到%s个用户--';
		$temp['schoolList'] = $schoolList;
		$temp['header'] = $this->getViewHeaderData();
		$temp['jsCtrl'] = 'userCtrl';
		$this->searchTpl->show($temp,$callback);
	}
	
	public function detail(){
		$uid = (int)$this->input->get_post('uid',TRUE);
		$format = $this->input->post_get('format',TRUE);
		$user = $this->users->findOneByID($uid);
		
		if( $format == 'json' ){
			if ( empty($user) ) {
				$this->apiOutput->error('无该用户');
				return FALSE;
			}
			$this->apiOutput->put('user', $user->toArray())->out();
			return TRUE;
		}
		
		if ( empty($user) ) {
			alert('无该用户');
			exit;
		}
		
		$temp['user'] = $user;
		$temp['schoolList'] = $this->school->getSchoolList();
		$header = array(
				'title'=>$user->nickname.'_用户资料',
				'placeList'=>array(
						array('title'=>'用户管理'),
						array('title'=>'用户列表'),
						array('title'=>'用户资料'),
						array('title'=>$user->nickname),
				),
		);
		$this->showView('admin/user/detail',$temp,$header);
	}
	
	public function update(){
		$user = $this->checkUidAndGetUser();
		$schoolID = (int)$this->input->post_get('schoolID');
		
		$res = $this->db->set('schoolID',$schoolID)
						->where('id',$user->id)
						->update(MY_Model::T_USER);
		$this->outUpdateResult($res);
	}
	/**
	 * 设为调试人员
	 */
	public function set_tester(){
		$user = $this->checkUidAndGetUser();
		$isTester = (int)$this->input->post_get('isTester');
		$res = $this->db->set('isTest',$isTester)
							->where('id',$user->id)
							->update(MY_Model::T_USER);
		$this->outUpdateResult($res);
		
		
	}
	/**
	 * 赠送水费
	 */
	public function presrent(){
		$user = $this->checkUidAndGetUser();
		
		$amount   = (int)$this->input->post('amount');
		$reason   = $this->input->post('reason',TRUE);
		
		if(  $amount <=0 ){
			$this->apiOutput->error('赠送金额必须大于0');
		}
		
		$this->load->model('Presrent_mdl','presrent');
		$admin = $this->admin->getUser() ;
		$res = $this->presrent->record($admin['id'],$user->id,$amount,$reason);
		if( $res ){
			$res = $this->db->set('presrent','presrent + '.$amount,FALSE)
							->set('balance','balance + '.$amount,FALSE)
							->where('id',$user->id)
							->update(MY_Model::T_USER);
		}
		$this->outUpdateResult($res);
	}
	/**
	 * 清空余额
	 */
	public function empty_balance(){
		$user = $this->checkUidAndGetUser();
		$admin = $this->admin->getUser() ;
		$this->load->model('Empty_balance_log_mdl','emptyLog');
		$res = $this->emptyLog->record($admin['id'],$user->id,$user->balance);
		if( $res ){
			$user->balance = 0;
			$res = $user->update();
		}
		$this->outUpdateResult($res);
	}
	/**
	 * API:取消绑定离线预授权手机
	 */
	public function unbind_offline_phone(){
		
		$user = $this->checkUidAndGetUser();
		$admin = $this->admin->getUser() ;
		
		$amount = $user->prepayment;
		$user->prepayment = 0;
		$user->balance+=$amount;
		$user->lockedPhoneID = NULL;
		$res = FALSE;
		if( $user->update() ){
			$this->load->model('Prepayment_log_mdl','prepaymentLog');
			$this->prepaymentLog->setUserID($user->id);
			$res = $this->prepaymentLog->transferOut($amount,$admin['id']);
		}
		$this->outUpdateResult($res);
	}
	
	private function checkUidAndGetUser(){
		$uid = (int)$this->input->get_post('uid');
		if( $uid <= 0 ){
			$this->apiOutput->errorInput();
		}
		$user = $this->users->findOneByID($uid);
		if( empty($user) ){
			$this->apiOutput->error('无该用户');
		}
		return $user;
	}
	private function outUpdateResult($res){
		$this->apiOutput->put('result', (int)$res)->out();
	}
	
	
	/**
	 * 合并账户
	 */
	public function combine(){
		if (empty ( $_REQUEST['submit'] )) {
			$temp = array ();
			$temp ['schoolList'] = $this->school->getSchoolList ();
			$this->showView ( 'admin/user/combine', $temp );
			return TRUE;
		}
		
		$mainUserID = ( int ) $this->input->post_get ( 'mid' );
		$delUserID = ( int ) $this->input->post_get ( 'did' );
		
		if ($mainUserID <= 0 || $delUserID <= 0) {
			$this->apiOutput->error ( '请输入账户ID', - 1 );
		}
		if ($mainUserID === $delUserID) {
			$this->apiOutput->error ( '主账户ID与废弃账户ID不能一样', - 2 );
		}
		$users = array (
				$mainUserID=>NULL,
				$delUserID=>NULL,
		);
		foreach ( $users as $uid=>&$user ) {
			$user = $this->users->getOneById($uid);
			if (empty ( $user )) {
				$this->apiOutput->error ( "找不到该用户(用户ID:$uid)", - 3 );
				return FALSE;
			}
			debug("user[$uid]",$user);
		}
		$users [$mainUserID] = $this->users->findOneByID($mainUserID);
		$users [$delUserID] = $this->users->findOneByID($delUserID);
// 		var_dump($users);die;
		
		$user = $this->users->combine ( $users [$mainUserID], $users [$delUserID] );
		
		if ( empty($user) ) {
			$this->apiOutput->errorSystem();
		}else {
			$this->apiOutput->put('user', $user->toArray())->out();
		}
	}
	
	
	
	
	
}

